package cn.edu.scut.fsearch.relative;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.nutch.util.NutchConfiguration;

import jeasy.analysis.MMAnalyzer;

public class RelativeQuery {

	private static Configuration conf; 
	private static String basePath;
	private static String INDEX_DIR;
	private static String FIELD_QUERY;
	private static String FIELD_WORD_TIME;
	
	public String[] getRelativeQuery(String query) throws IOException, ParseException{
		IndexSearcher is = new IndexSearcher(INDEX_DIR);
		QueryParser parser = new QueryParser(FIELD_QUERY, new MMAnalyzer());
		Query q = parser.parse(query);
		TopDocs docs = is.search(q,null,11,new Sort(FIELD_WORD_TIME));
		ScoreDoc[] scoreDocs = docs.scoreDocs;
		ArrayList<String> rq = new ArrayList<String>();
		for (int i=0,j=0; i<scoreDocs.length&&j<10; i++) {
			Document doc = is.doc(scoreDocs[i].doc);
			String relative = doc.get(FIELD_QUERY);
			if(!relative.equals(query)){
				rq.add(relative);
				j++;
			}
		}
		//is.close();
		return rq.toArray(new String[rq.size()]);
	}
	
	public RelativeQuery() {
		// TODO Auto-generated constructor stub
		init();
	}
	
	private void init() 
	{
		if (conf == null) 
		{
			conf = NutchConfiguration.create();
			basePath = conf.get("suggest.dir", "../webapps/ROOT/");
			INDEX_DIR = basePath + File.separatorChar + "query-index";
			FIELD_QUERY = "query";
			FIELD_WORD_TIME = "word_time";
		}
	}
	
	public static void main(String[] args){
		try{
			String queryString = "scut";
			RelativeQuery relativeQuery = new RelativeQuery();
			String[] rq= relativeQuery.getRelativeQuery(queryString);
			for (int i = 0; i < rq.length; i++)
			{
				System.out.println(rq[i]);
			}
			System.out.println("finished");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
}
